import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import {isArray} from "../../utils";
import {Slider} from "antd";
import useStateRef from "../../customUse/useStateRef.tsx";

interface InputNumberRangeProps {
    value: number[],
    ds?: any,
    disabled?: boolean,
    comProps?: any,
    onChange: Function
}


const InputNumberRange: FC<InputNumberRangeProps> = (props) => {

    const numberRangeRef = useRef([0, 0])
    const [numberRange, setNumberRange] = useStateRef([0, 0], numberRangeRef);

    const handleChange: Function = useCallback((value: any) => {
        setNumberRange(value);
        props.onChange && props.onChange(value);
    }, [props.onChange]);

    useEffect(() => {
        const {ds = {}}: { ds?: any } = props;
        let newValue = ds.value !== undefined ? ds.value : props.value;
        if (isArray(newValue) && JSON.stringify(newValue) !== JSON.stringify(numberRangeRef.current)) {
            setNumberRange(newValue);
        }
    }, [props.ds]);

    const renderInputNumberRange = useMemo(() => {
        const {disabled = false, comProps = {}}: { disabled?: boolean, comProps?: any } = props;
        return (
            <div className="sf_core_input_number_range">
                <Slider
                    {...comProps}
                    range
                    value={numberRange}
                    disabled={disabled}
                    style={{width: "100%"}}
                    onChange={handleChange}
                />
            </div>
        )
    }, [numberRange, props.onChange]);

    return (renderInputNumberRange);
};

export default React.memo(InputNumberRange);